﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Collections;

namespace CnGine.CodeGenerator.Help
{
    public class ServerHelper
    {

        private string _xmlPath = "";

        public string XmlPath
        {
            set { this._xmlPath = value; }
            get { return this._xmlPath; }
        }


        public void add(string ip, string username, string password)
        {
            XmlDocument xmlDoc = null;
            //加载XML文档  
            xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);
            XmlNode root = xmlDoc.SelectSingleNode("servers");
            try
            {
                XmlElement xe1 = xmlDoc.CreateElement("server");
                XmlElement xesub1 = xmlDoc.CreateElement("ip");
                xesub1.InnerText = ip;
                xe1.AppendChild(xesub1);
                XmlElement xesub2 = xmlDoc.CreateElement("username");
                xesub2.InnerText = username;
                xe1.AppendChild(xesub2);
                XmlElement xesub3 = xmlDoc.CreateElement("password");
                xesub3.InnerText = password;
                xe1.AppendChild(xesub3);
                //添加到根节点
                root.AppendChild(xe1);
            }
            catch (Exception ex)
            { }
            xmlDoc.Save(_xmlPath);
        }

        public void Update(string ip, string username, string password)
        {
            Delete(ip);
            add(ip, username, password);
        }
        public DataTable Read()
        {
            DataSet ds = new DataSet();
            ds.ReadXml(_xmlPath);
            if (ds != null & ds.Tables.Count > 0) return ds.Tables[0];
            else return new DataTable();
        }

        public void Delete(string ip)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(_xmlPath);
            XmlNode root = xmlDoc.SelectSingleNode("servers");
            XmlNodeList xnl = root.ChildNodes;

            for (int i = 0; i < xnl.Count; i++)
            {
                XmlNodeList xnl11 = xnl.Item(i).SelectNodes("ip");
                XmlElement xe = (XmlElement)xnl11.Item(0);
                if (xe.InnerText == ip)
                    root.RemoveChild(xe.ParentNode);
            }
            xmlDoc.Save(_xmlPath);
        }

    }
}
